package service

import (
	"fmt"
	"go-project/common"
	"go-project/dto/requrest"
	"go-project/models"
)

type Tag struct {
}

func (t Tag) FindLists(tagSearchReq *requrest.TagSearchRequest) (lists []models.Tag, count int64, err error) {
	offset := (tagSearchReq.Pagination.Page - 1) * tagSearchReq.Pagination.Limit
	var tag *models.Tag
	query := common.DB.Table(tag.TableName())
	if len(tagSearchReq.Name) > 0 {
		query = query.Where("name like ?", fmt.Sprintf("%%%s%%", tagSearchReq.Name))
	}
	query.Model(tag).Select("count(id)").Count(&count)
	err = query.Limit(tagSearchReq.Pagination.Limit).Order("id desc").Offset(offset).Find(&lists).Error
	return
}
func (Tag) Add(request *requrest.TagInsertRequest) (uint, error) {
	var tag models.Tag
	request.Generate(&tag)
	result := common.DB.Create(&tag)
	return tag.ID, result.Error
}

func (Tag) Update(request *requrest.TagUpdateRequest) (uint, error) {
	var model models.Tag
	row := common.DB.First(&model, request.Id)
	if row.Error != nil {
		return 0, row.Error
	}
	request.Generate(&model)
	result := common.DB.Save(&model)
	return model.ID, result.Error

}

func (Tag) Del(id uint) (uint, error) {
	var model models.Tag
	result := common.DB.Delete(&model, id)
	return uint(result.RowsAffected), result.Error
}
func (Tag) Get(id uint) (models.Tag, error) {
	var model models.Tag
	result := common.DB.First(&model, id)
	return model, result.Error
}

func (Tag) BatchDelByIds(ids []int) (uint, error) {
	var model models.Tag
	result := common.DB.Delete(&model, ids)
	return uint(result.RowsAffected), result.Error
}
